<?php

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;
use Imi\Config;

/**
 * 售后订单
 * @Auth(name="token",nologin={"no"})
 * @Controller("/store.aftersale/")
 */
class Aftersale extends StoreOwner
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];



    /**
     * 获取售后订单列表
     *
     * @param integer|null $page 1
     * @param integer|null $limit 10
     * @param string $refund_status 退款状态:-1=拒绝退款,0=未退款,1=同意
     * @param string $dispatch_status 发货状态:0=未发货,1=已发货,2=已收货
     * @param string $aftersale_status 售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成,3=全部
     * @param string $order 订单号
     * @return void
     * @Action
     */
    public function get_order_aftersale_list(?int $page = 1, ?int $limit = 10, $refund_status = null, $dispatch_status = null, $aftersale_status = null, $order = null)
    {
        $this->init();
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $where['store_id'] = $this->store_id;

        if ($order) {
            $where['refund_status'] = ['like', '%' . $order . '%'];
        }

        //退款
        if ($refund_status !== null && $refund_status != '') {
            $where['refund_status'] = $refund_status;
        }

        //售后
        if ($aftersale_status !== null && $aftersale_status != '') {
            if ($aftersale_status == '0') {
                $where['refund_status'] = '0';
            }
            $where['aftersale_status'] = $aftersale_status;
        }
        //发货状态
        if ($dispatch_status != null && $dispatch_status != '') {
            $where['dispatch_status'] = $dispatch_status;
        }




        $list = Db::name('order_aftersale')->whereIsNull('deletetime')->whereEx($where)->page($page, $limit)->orderRaw('createtime desc')->select()->getArray();
        foreach ($list as $key => &$val) {
            $val = $this->ItemChangeAftersaleOrder($val);
        }
        return $this->success('ok', $list);
    }




    /**
     * 子订单详情👔
     *
     * @param int $id 订单id
     * @return void
     * @Action
     */
    public function order_aftersale_detail(?int $id)
    {
        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order = Db::name('order_aftersale')
            // ->whereEx($this->whereCom)
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->select()->get();
        if ($order) {
            $order = $this->ItemChangeAftersaleOrderDetail($order);
        }
        return $this->success('order', $order);
    }




    /**
     * 同意退款(未发货的)
     *
     * @param int $id 订单id
     * @return void
     * @Action
     */
    public function agree_refund($id)
    {        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_aftersale = Db::name('order_aftersale')
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();

        if (!$order_aftersale) {
            return $this->error('没有该订单');
        }
        if ($order_aftersale['refund_status'] == '1') {
            //直接加余额 积分 贝壳退回


            return $this->error('已同意过');
        }

        //  `dispatch_status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '发货状态:0=未发货,1=已发货,2=已收货',
        //   `dispatch_fee` decimal(10,2) DEFAULT NULL COMMENT '发货费用',
        //   `aftersale_status` tinyint(2) NOT NULL COMMENT '售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成',
        //   `refund_status` tinyint(1) DEFAULT NULL COMMENT '退款状态:-1=拒绝退款,0=未退款,1=同意',
        //     type 类型:refund=退款,return=退货,other=其他'
        // if($order['type']=='refund'){
        $order_item = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
        if ($order_aftersale['refund_status'] == '0') {
           
            $order = $this->getOrderById($order_aftersale['order_id']);
            //直接加余额 积分 贝壳退回
            $data['order_id'] = $order_aftersale['order_id'];
            $data['order_item_id'] = $order_aftersale['order_item_id'];
            $data['oper_type'] = 'store';
            $data['oper_id'] = $this->store_id;
            // $data['order_status'] = $order['order_id']; //订单状态
            // $data['dispatch_status'] = $order_aftersale['dispatch_status']; //发货状态:0=未发货,1=已发货,2=已收货
            // $data['comment_status'] = $order_item['comment_status']; //评价状态:0=未评价,1=已评价
            $data['aftersale_status'] = '2'; //售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成
            $data['refund_status'] = '1'; //退款状态:-1=拒绝退款,0=未退款,1=同意
            $data['remark'] = '商家同意退款，立即到账';
            $data['createtime'] = time();
            $data['updatetime'] = time();

            $this->UpdateOrderAction($data);
            Db::name('order_aftersale')
                ->whereIsNull('deletetime')
                ->whereEx($where)
                ->update(['refund_status' => '1', 'updatetime' => time(), 'aftersale_status' => '2']);

            // if ($order_aftersale['refund_score'] > 0) {
            //     $this->IncUserScore($order_aftersale['user_id'], (float)$order_aftersale['refund_score'], '同意退款', 13, $id);
            // }

            // if ($order_aftersale['refund_shell'] > 0) {
            //     $this->IncUsershell($order_aftersale['user_id'], (float)$order_aftersale['refund_shell'], '同意退款', 13, $id);
            // }

            // //如果是微信和支付宝支付,原路退回
            // if ($order_aftersale['refund_fee'] > 0) {
            //     // $order
            //     $this->IncUserMoney($order_aftersale['user_id'], (float)$order_aftersale['refund_fee'], '同意退款', 13, $id);
            // }



            //如果这个最后一个退款,记得连运费一起退回
           

            $update_order_item['refund_status'] = '1'; //退款状态:-1=拒绝退款,0=无,1=申请中,2=同意
            $update_order_item['updatetime'] = time(); //
            $update_order_item['aftersale_status'] = '2'; //售后状态:-1=拒绝,0=未申请,1=申请售后,2=售后完成
            $update_order_item['status'] = '-2'; //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成

            Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->update($update_order_item);
            $this->storeOrderRefund($id);
            return $this->success('退款成功');
        }
        // }
        return $this->error('已拒绝状态');
    }






    /**
     * 同意退款(已发货的需要退货的)
     *
     * @param int $id 订单id
     * @param int $addr_id 退回地址
     * @param string $memo 备注
     * @return void
     * @Action
     */
    public function agree_refund2($id, $addr_id = null, $memo = null)
    {
        var_dump('同意退款agree_refund2');
        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_aftersale = Db::name('order_aftersale')
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();

        if (!$order_aftersale) {
            return $this->error('没有该订单');
        }

        // $str = '商家同意售后';
        if ($addr_id) {
            $addr = $this->GetStoreAddrData($addr_id);
            if ($addr) {
                // $str = $str.'退回地址'.''.$memo
                $update_data['store_phone']  = $addr['tel'];
                $update_data['consignee']  = $addr['name'];
                $update_data['address'] = $addr['province'] . $addr['city'] . $addr['district'] . $addr['town'] . $addr['addr'];
            }
        } else {
            return $this->error('请传递退货地址');
        }

        //refund_status 退款状态:-1=拒绝退款,0=未退款,1=同意
        if ($order_aftersale['refund_status'] == '0') {
            $order_data = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
            //直接加余额 积分 贝壳退回
            $操作记录['order_id'] = $order_aftersale['order_id'];
            $操作记录['order_item_id'] = $order_aftersale['order_item_id'];
            $操作记录['oper_type'] = 'store';
            $操作记录['oper_id'] = $this->store_id;
            // $操作记录['order_status'] = $order['order_id'];//订单状态
            // $操作记录['dispatch_status'] = $order_aftersale['dispatch_status']; //发货状态:0=未发货,1=已发货,2=已收货
            // $操作记录['comment_status'] = $order_data['comment_status']; //评价状态:0=未评价,1=已评价
            $操作记录['aftersale_status'] = '1'; //售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成
            $操作记录['refund_status'] = '1'; //退款状态:-1=拒绝退款,0=未退款,1=同意
            $操作记录['remark'] = '商家同意售后,请退货';
            $操作记录['createtime'] = time();
            $操作记录['updatetime'] = time();
            $this->UpdateOrderAction($操作记录);


            $update_data['refund_status'] = '1';
            $update_data['updatetime'] = time();
            $update_data['aftersale_status'] = '1';
            Db::name('order_aftersale')
                ->whereIsNull('deletetime')
                ->whereEx($where)
                ->update($update_data);

            //如果这个最后一个退款,记得连运费一起退回

            Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->update(['refund_status' => '1', 'updatetime' => time(), 'aftersale_status' => '1']);
            return $this->success('同意申请');
        }
        // }
        return $this->error('已拒绝状态');
    }



    /**
     * 换货上传单号
     * @param int $id 售后订单id
     * @param string $express_name 快递公司
     * @param string $express_no 快递编号
     * @Action
     */
    public function change_dispatch_express($id,$express_name=null,$express_no=null)
    {
        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_aftersale = Db::name('order_aftersale')
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();

        if (!$order_aftersale) {
            return $this->error('没有该订单');
        }


        $order_item =  $this->getOrderItemById($order_aftersale['order_item_id']);
        //Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();



        

        $快递包裹['user_id']  = $order_item['user_id'];//用户
        $快递包裹['store_id']  = $order_item['store_id'];//店铺
        $快递包裹['order_id']  = $order_item['order_id'];//订单
        $快递包裹['order_item_id']  = $order_item['id'];//子订单
        $快递包裹['express_name']  = $express_name;//快递公司
        $快递包裹['express_no']  = $express_no;//快递单号
        $快递包裹['createtime']  = time();
        $快递包裹['updatetime']  = time();
        $快递包裹['status']  = '3';//状态:1=卖家正常发货,2=用户售后,3=卖家换货
        $this->AddOrderExpress($快递包裹);


        //退款状态:-1=拒绝退款,0=未退款,1=同意
        if ($order_aftersale['refund_status'] != '-1' && $order_aftersale['aftersale_status'] != '-1') {
            // $order_data = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
            //直接加余额 积分 贝壳退回            $data['order_id'] = $order_aftersale['order_id'];
            $data['order_item_id'] = $order_aftersale['order_item_id'];
            $data['oper_type'] = 'store';
            $data['oper_id'] = $this->store_id;

         

            $data['remark'] = '卖家换货发货';
            $data['createtime'] = time();
            $data['updatetime'] = time();


            $update_data['updatetime'] = time();
            $this->UpdateOrderAction($data);
            Db::name('order_aftersale')
                ->whereIsNull('deletetime')
                ->whereEx($where)
                ->update($update_data);

            $update_order_item['store_express_name'] = $express_name;
            $update_order_item['store_express_no'] = $express_no;
            $update_order_item['updatetime'] = time();

            Db::name('order_aftersale')->where('id', '=', $id)->update($update_order_item);
            return $this->success('发货成功');
        }

        return $this->error('非同意状态');
    }

    //收到货以后直接退款


    /**
     * 同意退款
     *
     * @param int $id 订单id
     * @return void
     * @Action
     */
    public function agree_refund3($id)
    {
        var_dump('同意退款agree_refund3');
        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_aftersale = Db::name('order_aftersale')
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();

        if (!$order_aftersale) {
            return $this->error('没有该订单');
        }
       
        // $str = '商家同意退款';
        // if ($addr_id) {
        //     $addr = GetStoreAddrData($addr_id);
        //     if ($addr) {
        //         // $str = $str.'退回地址'.''.$memo
        //         $update_data['store_phone']  = $addr['tel'];
        //         $update_data['consignee']  = $addr['name'];
        //         $update_data['address'] = $addr['province'] . $addr['city'] . $addr['district'] . $addr['town'] . $addr['addr'];
        //     }
        // }

        //  `dispatch_status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '发货状态:0=未发货,1=已发货,2=已收货',
        //   `dispatch_fee` decimal(10,2) DEFAULT NULL COMMENT '发货费用',
        //   `aftersale_status` tinyint(2) NOT NULL COMMENT '售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成',
        //   `refund_status` tinyint(1) DEFAULT NULL COMMENT '退款状态:-1=拒绝退款,0=未退款,1=同意',
        //     type 类型:refund=退款,return=退货,other=其他'
        // if($order['type']=='refund'){
        if ($order_aftersale['refund_status'] != '-1' && $order_aftersale['aftersale_status'] != '-1') {
            $order_data = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
            //直接加余额 积分 贝壳退回
            $操作订单['order_id'] = $order_aftersale['order_id'];
            $操作订单['order_item_id'] = $order_aftersale['order_item_id'];
            $操作订单['oper_type'] = 'store';
            $操作订单['oper_id'] = $this->store_id;
            // $操作订单['order_status'] = $order['order_id'];//订单状态
        

            $操作订单['aftersale_status'] = '2'; //售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成
            $操作订单['refund_status'] = '1'; //退款状态:-1=拒绝退款,0=未退款,1=同意
            $操作订单['remark'] = '商家已确认到货，同意退款';
            $操作订单['createtime'] = time();
            $操作订单['updatetime'] = time();
            $this->UpdateOrderAction($操作订单);

            $update_data['refund_status'] = '1';
            $update_data['updatetime'] = time();
            $update_data['aftersale_status'] = '2';
            Db::name('order_aftersale')
                ->whereIsNull('deletetime')
                ->whereEx($where)
                ->update($update_data);

            //如果这个最后一个退款,记得连运费一起退回

         

            Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->update(['refund_status' => '1', 'updatetime' => time(), 'aftersale_status' => '2']);
            $this->storeOrderRefund($id);
            return $this->success('退款成功');
        }
        // }
        return $this->error('已拒绝状态');
    }



    /**
     * 拒绝退款
     *
     * @param int $id 订单id
     * @param string $memo 拒绝理由
     * @return void
     * @Action
     */
    public function refuse_refund($id, $memo = null)
    {
        $this->init();
        $where['id'] = $id;
        $where['store_id'] =  $this->store_id;
        $order_aftersale = Db::name('order_aftersale')
            ->whereEx($where)
            ->whereIsNull('deletetime')
            ->find();

        if (!$order_aftersale) {
            return $this->error('没有该订单');
        }
        if ($order_aftersale['refund_status'] == '1') {
            return $this->error('已同意过');
        }

        //  `dispatch_status` tinyint(2) NOT NULL DEFAULT '0' COMMENT '发货状态:0=未发货,1=已发货,2=已收货',
        //   `dispatch_fee` decimal(10,2) DEFAULT NULL COMMENT '发货费用',
        //   `aftersale_status` tinyint(2) NOT NULL COMMENT '售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成',
        //   `refund_status` tinyint(1) DEFAULT NULL COMMENT '退款状态:-1=拒绝退款,0=未退款,1=同意',
        //     type 类型:refund=退款,return=退货,other=其他'
        // if($order_aftersale['type']=='refund'){
        if ($order_aftersale['refund_status'] == '0') {
            $order_data = Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->find();
            // $order = $this->getOrderById($order_aftersale['order_id']);
            //直接加余额 积分 贝壳退回
            $data['order_id'] = $order_aftersale['order_id'];
            $data['order_item_id'] = $order_aftersale['order_item_id'];
            $data['oper_type'] = 'store';
            $data['oper_id'] = $this->store_id;
            // $data['order_status'] = $order['status']; //订单状态
            // $data['dispatch_status'] = $order_aftersale['dispatch_status']; //发货状态:0=未发货,1=已发货,2=已收货
            // $data['comment_status'] = $order_data['comment_status']; //评价状态:0=未评价,1=已评价
            $data['aftersale_status'] = '-1'; //售后状态:-1=拒绝,0=未处理,1=处理中,2=售后完成
            $data['refund_status'] = '-1'; //退款状态:-1=拒绝退款,0=未退款,1=同意
            $data['remark'] = '商家拒绝退款_商家理由:' . $memo;
            $data['createtime'] = time();
            $data['updatetime'] = time();

            $this->UpdateOrderAction($data);
            Db::name('order_aftersale')
                ->whereIsNull('deletetime')
                ->whereEx($where)
                ->update(['refund_status' => '-1', 'updatetime' => time(), 'memo' => $memo, 'aftersale_status' => '-1']);

            Db::name('order_item')->where('id', '=', $order_aftersale['order_item_id'])->update(['refund_status' => '-1', 'updatetime' => time(), 'aftersale_status' => '-1']);
            return $this->success('拒绝成功');
        }
        // }
        return $this->error('非待处理状态');
    }




    /**
     * 售后
     *
     * @param array $val
     * @return void
     */
    protected function ItemChangeAftersaleOrder($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order_item'] = Db::name('order_item')->where('id', '=', $val['order_item_id'])->find();
        $val['order'] = Db::name('order')->where('id', '=', $val['order_id'])->find();
        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);
        return $val;
    }



    /**
     * 售后
     *
     * @param array $val
     * @return void
     */
    protected function ItemChangeAftersaleOrderDetail($val)
    {
        $val['user'] = $this->GetUserData2($val['user_id']);
        $val['order_item'] = Db::name('order_item')->where('id', '=', $val['order_item_id'])->find();
        $order = Db::name('order')->where('id', '=', $val['order_id'])->find();
        if ($order) {
            $order['date'] = date('Y-m-d H:i:s', $order['createtime']);
            $val['order'] = $order;
        }
        $val['date'] = date('Y-m-d H:i:s', $val['createtime']);

        if($val['type']=='change' || $val['type'] == 'return'){
            $where['order_id'] = $val['order_id'];
            $where['order_item_id'] = $val['order_item_id'];
            $val['order_express'] = Db::name('order_express')->whereEx($where)->orderRaw('id desc')->select()->getArray();
        }



        return $val;
    }
}
